dict = {'name':'ss','age':18}
print(dict)

# 查看元素
print(dict['name'])
print(dict['age'])
# print(dict['sex'])  KeyError: 'sex'

print(dict.get('name'))
print(dict.get('sex')) # None
print(dict.get('sex','不存在')) # 不存在

# 修改元素
dict['age'] = 20
print(dict)

# 新增元素
dict['sex'] = '男'
print(dict)

dict['sex'] = '女'
print(dict)

# 删除元素
dict1 = {'name':'ss','age':18,'tel':'123456'}
print(dict1)
# del dict1
# print(dict1)
# del dict1['age']
# print(dict1)

# del dict1['ge']
# print(dict1)

# dict1.clear()
# print(dict1)

# dict1.pop('age')
# print(dict1)
# dict1.pop('name')
# print(dict1)
# dict1.pop('name')
# print(dict1)

# dict1.popitem() #删除最后一个
# print(dict1)

# 字典的操作
dict2 = {'name':'ss','age':18,'tel':'123456','sex':'男','job':'python开发'}

print(len(dict2)) # 5

print(dict2.keys())
for key in dict2.keys():
    print(key,end=' ')
    print(dict2.get(key))

print(dict2.values())
for value in dict2.values():
    print(value)

print(dict2.items()) # 元组形式





# cars = {'AUDI': 7.9, 'BENS': 8.3, 'BMW': 8.5}
# print(cars)# 弹出字典底层存储的最后一个key-value对
# print(cars.popitem()) # ('AUDI', 7.9)
# print(cars) # {'BMW': 8.5, 'BENS': 8.3}
#
# k, v = cars.popitem()
# print(k, v) # BENS 8.3


cars = {'BMW': 8.5, 'BENS': 8.3, 'AUDI': 7.9}
# 设置默认值，该key在dict中不存在，新增key-value对
print(cars.setdefault('PORSCHE', 9.2)) # 9.2
print(cars)
# 设置默认值，该key在dict中存在，不会修改dict内容
print(cars.setdefault('BMW', 3.4)) # 8.5
print(cars)
